using Godot;
using System;
using System.Diagnostics;

public partial class Player : CharacterBody2D
{
	[Export] float SPEED = 100.0f;

	[Export] float ROLL_SPEED = 125.0f;

	private Vector2 inputVector = Vector2.Zero;
	private Vector2 lastInputVector = Vector2.Zero;

	private AnimationTree animationTree;

	private AnimationNodeStateMachinePlayback playback;

	public override void _Ready()
	{
		animationTree = GetNode<AnimationTree>("AnimationTree");
		playback = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/StateMachine/playback");
	}


	public override void _PhysicsProcess(double delta)
	{
	   
		string curNode = playback.GetCurrentNode();

		switch (curNode)
		{
			case "MoveState":
				MoveState(delta);
				break;
			case "AttackState":
				break;
			case "RollState":
				RollState();
				break;
		}
		
	   
	}

	private void RollState()
	{
		Velocity = lastInputVector * ROLL_SPEED;
		MoveAndSlide();
	}


	private void MoveState(double delta)
	{
		inputVector = Input.GetVector("move_left", "move_right", "move_up", "move_down");

		if (inputVector != Vector2.Zero)
		{
			lastInputVector = inputVector;
			Vector2 directionVector = new Vector2(inputVector.X, -inputVector.Y);
			UpdateBlendPosition(directionVector);
		}

		if (Input.IsActionJustPressed("attack"))
		{  
			playback.Travel("AttackState");        
		}

		if (Input.IsActionJustPressed("roll"))
		{ 
			playback.Travel("RollState");        
		}

		Velocity = inputVector * SPEED;

		MoveAndSlide();
	}

	private void UpdateBlendPosition(Vector2 directionVector)
	{
		animationTree.Set("parameters/StateMachine/MoveState/RunState/blend_position", directionVector);
		animationTree.Set("parameters/StateMachine/MoveState/StandState/blend_position", directionVector);
		animationTree.Set("parameters/StateMachine/AttackState/blend_position", directionVector);
		animationTree.Set("parameters/StateMachine/RollState/blend_position", directionVector);
	}
}
